package com.lechi.web.runner;

import com.lechi.iot.client.AppClient;
import com.lechi.iot.client.COMMAND;
import com.lechi.web.common.config.LeChiConfig;
import com.lechi.web.constants.Constants;
import com.lechi.web.framework.util.GuavaCacheUtil;
import com.lechi.web.service.IIotGatewayService;
import com.lechi.web.system.domain.IotDeviceBo;
import com.lechi.web.system.domain.IotGatewayBo;
import com.lechi.web.system.domain.IotMonitorDataBo;
import com.lechi.web.system.mapper.iot.IotDeviceMapper;
import com.lechi.web.system.mapper.iot.IotMonitorDataMapper;
import com.lechi.web.util.LeChiCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 开启网关端口监听，更新网关状态打开，初始化设备状态为未连接
 *
 * @author yangguang
 */
@Slf4j
@Order(2)
@Component("StartTCPGateWay")
public class StartTCPGateWay implements CommandLineRunner {

    public static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(4);

    @Autowired
    private IIotGatewayService iotGatewayService;

    @Autowired
    private IotDeviceMapper iotDeviceMapper;

    @Autowired
    private LeChiConfig leChiConfig;


    @Autowired
    private IotMonitorDataMapper iotMonitorDataMapper;

    public void run(String... args) throws SchedulerException {
        if ("DaPeng".equals(leChiConfig.getName())) {
            return;
        }

        iotGatewayService.selectIotGatewayList(new IotGatewayBo()).forEach(iotDevice -> {
//            if (iotDevice.getPort() == 18081) {
//                iotDevice.setPort(18080L);
//            }
            iotGatewayService.start(iotDevice);
            IotGatewayBo gateway = new IotGatewayBo();
            if (Objects.equals(iotDevice.getStatus(), Constants.CLOSE_STATUE)) {
                gateway.setId(iotDevice.getId());
                gateway.setStatus(Constants.SOCKT_OPEN_STATUE);
                iotGatewayService.updateIotGateway(gateway);
            }
        });
        iotDeviceMapper.selectIotDeviceListForSchedule().forEach(iotDeviceBo -> {
            GuavaCacheUtil.getBiDeviceSnAndIPMap().putIfAbsent(iotDeviceBo.getDeviceSn(), iotDeviceBo.getDeviceSn());
        });
        LeChiCacheUtil.androidOfflineLogTask();

        startXiAnQXJ();
    }

    /**
     * 启动西安气象局
     */
    public void startXiAnQXJ() {
        IotDeviceBo iotDeviceBo = iotDeviceMapper.selectIotDeviceById(303L);
        if (Objects.isNull(iotDeviceBo)) {
            return;
        }
        uploadDataToXiAn();
        CompletableFuture.runAsync(() -> {
            try {
                AppClient appClient = new AppClient(60000);
                appClient.connect(COMMAND.QIXIANGJU_IP, 18089, 30000);
            } catch (Exception e) {
                log.error("采集器客户端连接服务端地址：{}端口：{}，异常", e);
            }
        });
    }

    public void uploadDataToXiAn() {
        scheduler.scheduleAtFixedRate(() -> {
            queryData("iot_monitor_data_303", 2103L, "FY001");
            queryData("iot_monitor_data_304", 2106L, "FY002");
            queryData("iot_monitor_data_305", 2109L, "FY003");
        }, 60 - LocalDateTime.now().getSecond(), 60, TimeUnit.SECONDS);
    }

    private void queryData(String tableName, Long sensorAliasId, String stationNum) {
        Map<String, Object> params = new HashMap<>();
        LocalDateTime endTime = LocalDateTime.now().withSecond(0).withNano(0);
        LocalDateTime startTime = endTime.minusMinutes(10).withNano(0);
        params.put("beginTime", startTime.toString().replace("T", " "));
        params.put("endTime", endTime.toString().replace("T", " "));
        IotMonitorDataBo iotMonitorDataBo = new IotMonitorDataBo();
        iotMonitorDataBo.setTableName(tableName);
        iotMonitorDataBo.setParams(params);
        iotMonitorDataBo.setSensorAliasId(sensorAliasId);
        Long value = iotMonitorDataMapper.selectAvgMonitorData(iotMonitorDataBo);
        String message = String.format("$DATADICK,V202501,%s,YITWS00,N01,OB,%s,ASA,%s,z,0,", stationNum,
                LocalDateTime.now().format(COMMAND.yyyyMMddHHmmss), Objects.isNull(value) ? 3139 : value);
        String checkCode = String.format("%04d", message.substring(1).chars().sum() % 10000);
        COMMAND.send(message + checkCode + COMMAND.END + COMMAND.RESPONSE_END);
    }
}


